package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ：HX
 * @date ：Created in 2019/12/13
 * @description ：
 * @version: 1.0
 */
@Service
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Role> page = roleDao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(Integer[] permissionIds, Integer[] menuIds, Role role) {
//        新增角色信息
        roleDao.add(role);
//        新增角色和权限关系
//        新增角色和菜单关系
        addRoleAndPermission(permissionIds,menuIds,role.getId());
    }

    @Override
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    @Override
    public void edit(Integer[] permissionIds, Integer[] menuIds, Role role) {
//        更新角色基本信息
        roleDao.edit(role);
//        删除角色和权限和菜单的关系
        roleDao.deleteAssociationRoleAndPermission(role.getId());
        roleDao.deleteAssociationRoleAndMenu(role.getId());
//        新增角色和权限关系
//        新增角色和菜单关系
        addRoleAndPermission(permissionIds,menuIds,role.getId());
    }

    @Override
    public void deleteById(Integer id) {
 //        通过Id查看角色是否和用户关联
        Long count=roleDao.findAssociationByRoleId(id);
        if (count>0){
            throw new RuntimeException(MessageConstant.ROLE_HAS_ASSOCIATION);
        }
//        删除和权限和菜单的关系
        roleDao.deleteAssociationRoleAndPermission(id);
        roleDao.deleteAssociationRoleAndMenu(id);
//        删除角色的基本信息
        roleDao.deleteById(id);
    }

    public void addRoleAndPermission(Integer[] permissionIds,Integer[] menuIds,Integer roleId){
        if (permissionIds!=null&&permissionIds.length>0) {
            for (Integer permissionId : permissionIds) {
                Map map=new HashMap();
                map.put("permissionId",permissionId);
                map.put("roleId",roleId);
                roleDao.addRoleAndPermission(map);
            }
        }
        if (menuIds!=null&&menuIds.length>0) {
            for (Integer menuId: menuIds) {
                Map map=new HashMap();
                map.put("menuId",menuId);
                map.put("roleId",roleId);
                roleDao.addRoleAndMenu(map);
            }
        }
    }
}
